<template>
  <div>
    <div style="margin-bottom: 10px;overflow: hidden">
      <div style="float: left;">
        <Button type="success" icon="person-add" @click.native="handleAddOrUpdate()">新建快速链接</Button>
        <Button type="warning" icon="trash-a" @click.native="handleDelete()" :disabled="dataListSelections.length <= 0">批量删除</Button>
      </div>
      <div style="float: right;">
        <Row>
          <Input v-model="dataForm.name" icon="ios-search" placeholder="请输入标题名搜索..." style="width: 200px" clearable/>
          <span @click="getDataList" style="margin: 0 10px;"><Button type="primary" icon="search">搜索</Button></span>
        </Row>
      </div>
    </div>
    <Table border
           size="small"
           ref="selection"
           :columns="columns"
           :data="dataList"
           :loading="dataListLoading"
           @on-selection-change="handleSelectionChange"
           @on-row-click="handleSelectOne"
           stripe></Table>
    <div style="margin: 10px;overflow: hidden">
      <div style="float: right;">
        <Page
          :total="totalPage"
          size="small"
          :page-size="pageSize"
          :page-size-opts="[10,20,30,50,100]"
          :current="pageIndex"
          @on-change="handleCurrentChange"
          @on-page-size-change="handleSizeChange"
          show-elevator
          show-sizer
          show-total></Page>
      </div>
    </div>
    <add-or-update v-if="addOrUpdateVisiable"
                   ref="addOrUpdate"
                   @refreshDataList="getDataList"
    >
    </add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './link-add-update';
// import util from '@/libs/util';
export default {
  data () {
    return {
      columnId: 0,
      /* 查询项 */
      dataForm: {
        userId: 0,
        name: ''
      },
      // 数据列表
      dataList: [],
      // 当前页
      pageIndex: 1,
      // 每页数据条数
      pageSize: 10,
      // 总页数
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisiable: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '标题',
          key: 'title'
        },
        {
          title: '导航链接',
          key: 'linkUrl'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            const id = params.row.id;
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  icon: 'edit'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: (e) => {
                    this.handleAddOrUpdate(id);
                    // js原生阻止事件冒泡
                    e.stopPropagation();
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'warning',
                  // shape: 'circle',
                  size: 'small',
                  icon: 'trash-a'
                },
                on: {
                  click: (e) => {
                    this.handleDelete(id);
                    e.stopPropagation();
                  }
                }
              }, '删除')
            ]);
          }
        }
      ]
    }
  },
  components: {
    AddOrUpdate
  },
  created () {
    this.getDataList();
  },
  activated () {
    /* todo:不执行，原理暂不清楚
            */
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/link/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'title': this.dataForm.name
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      })
    },
    // 每页显示数据条数变化
    handleSizeChange (val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页码变化
    handleCurrentChange (val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    handleSelectionChange (val) {
      this.dataListSelections = val;
    },
    // 单选（点击行选中）
    handleSelectOne (val, index) {
      this.$refs.selection.toggleSelect(index);
    },
    // 新增、修改弹窗
    handleAddOrUpdate (id) {
      console.log(id)
      if (id === undefined) {
        console.log('新增文章')
        /* 新增发布文章 */
        this.$http({
          url: this.$http.adornUrl('/link/save'),
          method: 'post',
          data: this.$http.adornData({
            'title': '新建快速链接',
            'linkUrl': 'https://www.baidu.com'
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            id = data.link.id;
            console.log(id);
            /* */
            this.addOrUpdateVisiable = true;
            this.$nextTick(() => {
              this.$refs.addOrUpdate.init(id);
            });
          } else {
            console.log('后台异常')
          }
        })
      } else {
        /* */
        this.addOrUpdateVisiable = true;
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id);
        });
      }
    },
    // 新增修改提交
    /* handleSubmit () {
                 this.$refs.addOrUpdate.handleSubmit();
             }, */
    // 删除
    handleDelete (id) {
      let ids = [];
      if (id != null) {
        ids.push(id);
      }
      this.dataListSelections.forEach(function (value, index) {
        ids.push(value.id);
      });
      this.dataListLoading = true;
      this.$Modal.confirm({
        title: '删除操作',
        content: `确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`,
        onOk: () => {
          this.$http({
            url: this.$http.adornUrl('/link/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.pageIndex = 1;
              this.$Message.info({
                content: '操作成功',
                onClose: () => {
                  this.dataListSelections.length = 0;
                  this.getDataList();
                  this.dataListLoading = false;
                }
              });
            } else {
              this.$Message.error(data.msg);
            }
          })
        },
        onCancel: () => {
          /* 取消回调 */
          this.dataListLoading = false;
        }
      });
    }
    // 导出
  }
}
</script>

<style scoped>

</style>
